//
//  FreshHallSectionView.m
//  Youhuiju
//
//  Created by 余尚飞 on 16/8/11.
//  Copyright © 2016年 yutenys. All rights reserved.
//

#import "FreshHallSectionView.h"

#import "FreshSectionViewCollectionViewCell.h"

@interface FreshHallSectionView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *collectionView;

@property(nonatomic,strong)UIButton *leftBtn;//牛肉

@property(nonatomic,strong)UIButton *rightBtn;//羊肉

//@property(nonatomic,strong)UIButton *pullDownBtn;//下拉button

@property(nonatomic,strong)UIImageView *lineImg;//底部点击滑动小条

@property(nonatomic,assign)NSInteger flag;//当前选中item的序号



//占位数据
@property(nonatomic,strong)NSArray *dataArray;
@end


@implementation FreshHallSectionView

CGFloat collectionWid = 0;


static NSString *FreshSectionViewCollectionViewCellIden = @"FreshSectionViewCollectionViewCellIden";

//static BOOL isClickedItem = NO;

static id _shareInstance = nil;

+(instancetype)getInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shareInstance = [[self alloc]init];
    });
    return _shareInstance;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    _shareInstance = [super initWithFrame:frame];
    
    [self creatView];
    
    return _shareInstance;
}

-(void)creatView
{
    self.flag = 0;
    self.dataArray = @[@"牛腩排（F肉）",@"里脊（牛柳）",@"肋排",@"臀肉",@"膝园（和尚头，圆霖）",@"粗膝圆",@"眼肉"];
//    self.dataArray = @[@"爆款直降",@"精品美妆",@"洗护沐浴",@"品质家具",@"澳洲生鲜",@"品质母婴"];
    self.leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.leftBtn.tag = 0;
    self.leftBtn.tintColor = [UIColor blackColor];
    self.leftBtn.backgroundColor = [UIColor whiteColor];
    [self.leftBtn setTitle:@"牛肉" forState:UIControlStateNormal];
    [self.leftBtn addTarget:self action:@selector(buttonClickedAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.leftBtn];
    [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top);
        make.left.equalTo(self.mas_left);
        make.size.mas_equalTo(CGSizeMake(187 * FitW, 41 * FitH));
    }];
    
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.rightBtn.tag = 1;
    self.rightBtn.tintColor = [UIColor blackColor];
    self.rightBtn.backgroundColor = [UIColor whiteColor];
    [self.rightBtn setTitle:@"羊肉" forState:UIControlStateNormal];
    [self.rightBtn addTarget:self action:@selector(buttonClickedAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.rightBtn];
    [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.leftBtn.mas_top);
        make.left.equalTo(self.leftBtn.mas_right).offset(1 * FitW);
        make.size.mas_equalTo(CGSizeMake(187 * FitW, 41 * FitH));
    }];
    
    
    //底部动画小条
    self.lineImg = [[UIImageView alloc]init];
    self.lineImg.backgroundColor = [UIColor colorWithHexString:@"fd743e"];
    [self addSubview:self.lineImg];
    [self.lineImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.leftBtn.mas_bottom);
        make.left.equalTo(self.mas_left).priorityLow();
        make.size.mas_equalTo(CGSizeMake(187 * FitW, 2 * FitH));
    }];
    
    //下拉按钮
    
    self.pullDownBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    self.pullDownBtn.backgroundColor = [UIColor redColor];
    [self.pullDownBtn setBackgroundImage:LoadImage(@"heixia") forState:UIControlStateNormal];
    self.pullDownBtn.tag = 2;
    [self addSubview:self.pullDownBtn];
    [self.pullDownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right).offset(-10 * FitW);
        make.bottom.equalTo(self.mas_bottom).offset(-5 * FitH);
        make.size.mas_equalTo(CGSizeMake(30 * FitW, 30 * FitH));
    }];
    [self.pullDownBtn addTarget:self action:@selector(buttonClickedAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    _flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumInteritemSpacing = 0 * FitH;
    _flowLayout.minimumLineSpacing = 10 * FitW;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.top.equalTo(self.lineImg.mas_bottom);
        make.right.equalTo(self.mas_right).offset(-50 * FitW);
        make.bottom.equalTo(self.mas_bottom);
    }];
    [self.collectionView registerNib:[UINib nibWithNibName:@"FreshSectionViewCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:FreshSectionViewCollectionViewCellIden];
    
}

#pragma mark -------- collectionView delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
//    DLog(@"%.f------",[self WidthWithString:self.dataArray[indexPath.row] fontSize:13 * FitH height:24 * FitH ] ) ;
    
    return CGSizeMake(([self WidthWithString:self.dataArray[indexPath.row] fontSize:13 * FitH height:24 * FitH ] + 10 * FitW) , 24 * FitH);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FreshSectionViewCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:FreshSectionViewCollectionViewCellIden forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor greenColor];
    cell.dataString = self.dataArray[indexPath.row];
    
//    if ( indexPath.row == self.flag   )
//    {
//        cell.backgroundColor = [UIColor colorWithHexString:@"fd743e"];
//        cell.sectionTitleLabel.textColor = [UIColor whiteColor];
//    }else{
//        cell.sectionTitleLabel.textColor = [UIColor colorWithHexString:@"666666"];
//        cell.backgroundColor = [UIColor clearColor];
//    }
//    
    if ( indexPath.row == self.num   )
    {
        cell.backgroundColor = [UIColor colorWithHexString:@"fd743e"];
        cell.sectionTitleLabel.textColor = [UIColor whiteColor];
    }else{
        cell.sectionTitleLabel.textColor = [UIColor colorWithHexString:@"666666"];
        cell.backgroundColor = [UIColor clearColor];
    }
    
//    if ( indexPath.row == self.num - 1  )
//    {
//        cell.backgroundColor = [UIColor whiteColor];
//        cell.titleLabel.textColor = [UIColor colorWithHexString:@"ff5f7d"];
//    }else{
//        cell.backgroundColor = [UIColor clearColor];
//        cell.titleLabel.textColor = [UIColor whiteColor];
//    }
    
    return cell;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10 * FitH, 12 * FitW, 10 * FitH, 10 * FitW);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 9 * FitW;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    
    DLog(@"%zd-----%@",indexPath.row,self.dataArray[indexPath.row]);
    
//    self.flag = indexPath.row;
//     DLog(@"%zd-----%@",self.flag,self.dataArray[indexPath.row]);
//    
//    if (self.flag >= 1 && self.flag < self.dataArray.count - 1)
//    {
//        NSInteger collectionWid = 0;
//        for (NSInteger j = 2; j < indexPath.row + 1; j ++)
//        {
//            collectionWid += [self WidthWithString:self.dataArray[j] fontSize:13  height:24 ] + 20 ;
//            DLog(@"collWid1:---------%zd--------%zd",collectionWid,[self WidthWithString:self.dataArray[j] fontSize:13 * FitH height:24 * FitH]);
//        }
//        if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
//            
//            [self.collectionView setContentOffset:CGPointMake(collectionWid , 0) animated:YES];
//            DLog(@"collWid2:------------%zd---------%f",collectionWid,self.collectionView.contentOffset.x);
//        }
//
//
//    }
//    [self.sectionDelegate changeTableViewContentOffset:self.flag];
//    
//    //    SectionLabelCollectionViewCell * cell = [];
//    
//    
//    [self.collectionView reloadData];//不能用这个，，直接刷新tableView 的 cell

    self.num = indexPath.row ;
    
    
    DLog(@"%zd-----%@",indexPath.row,self.dataArray[indexPath.row]);
    
    //    self.num = indexPath.row;
    DLog(@"%zd-----%@",self.num,self.dataArray[indexPath.row]);
    
    if (self.num - 1 >= 1 && self.num - 1 < self.dataArray.count - 1)
    {
        NSInteger collectionWid = 0;
        for (NSInteger j = 2; j < self.num + 1; j ++)
        {
            collectionWid += [self WidthWithString:self.dataArray[j] fontSize:13 * FitH height:24 * FitH] + 9 * FitW;
            DLog(@"collWid1:---------%zd--------%zd",collectionWid,[self WidthWithString:self.dataArray[j] fontSize:13 * FitH height:24 * FitH]);
        }
        if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
            
            [self.collectionView setContentOffset:CGPointMake(collectionWid * FitW, 0) animated:YES];
            DLog(@"collWid2:------------%zd---------%f",collectionWid,self.collectionView.contentOffset.x);
        }
        
        
    }
    [self.sectionDelegate changeTableViewContentOffset:self.num ];
    
    [self.collectionView reloadData];//不能用这个，，直接刷新tableView 的 cell
    
    
    
    
}


-(void)buttonClickedAction:(UIButton *)sender
{
    
    if (self.buttonClickedHandler)
    {
        self.buttonClickedHandler(sender.tag,12);
    }
    [self.lineImg mas_updateConstraints:^(MASConstraintMaker *make) {
        
        if (sender.tag == 0)
        {
            make.left.equalTo(self.rightBtn.mas_left).offset(-188 * FitW);
        }
        else if(sender.tag == 1)
        {
            make.left.equalTo(self.rightBtn.mas_left);
        }
    }];
    
    
}

-(CGFloat)WidthWithString:(NSString *)string fontSize:(CGFloat)fontSize height:(CGFloat)height;
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    return  [string boundingRectWithSize:CGSizeMake(0, height) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.width;
}

//传值联动
-(void)setNum:(NSInteger)num
{
//    if (_num != num)
//    {
//        _num = num;
//
//        
//            if (num  >= 1 && num  < self.dataArray.count - 1)
//            {
//                NSInteger collectionWid = 0;
//                for (NSInteger j = 2; j < num + 1; j ++)
//                {
//                    collectionWid += [self WidthWithString:self.dataArray[j] fontSize:13 * FitH height:24 * FitH] + 9 * FitW;
//                }
//                if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
//                    
//                    [self.collectionView setContentOffset:CGPointMake(collectionWid * FitW, 0) animated:YES];
//                }
//            }
//            
//            [self.collectionView reloadData];//不能用这个，，直接刷新tableView 的 cell
////        }
//        
//    }
    
    DLog(@"--------self.num:%zd",num);
    if (_num != num)
    {
        _num = num;
        
        if (num - 1 >= 1 && num - 1 < self.dataArray.count - 1)
        {
            NSInteger collectionWid = 0;
            for (NSInteger j = 2; j < num + 1; j ++)
            {
                collectionWid += [self WidthWithString:self.dataArray[j] fontSize:13 * FitH height:24 * FitH] + 9 * FitW;
            }
            if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
                
                [self.collectionView setContentOffset:CGPointMake(collectionWid * FitW, 0) animated:YES];
            }
        }else if (num == 1)
        {
            [self.collectionView setContentOffset:CGPointMake(0 * FitW, 0) animated:YES];
        }
        
        [self.collectionView reloadData];//不能用这个，，直接刷新tableView 的 cell
        
    }
    
    
}

@end
